<template>
  <div class="register-container">
    <!-- 左侧内容区域，PC 端显示，H5 端可根据需求决定是否隐藏或调整 -->
    <div class="left-section" :class="{ 'hide-on-mobile': isMobile }">
      <h1 class="system-title">学生质量评价系统</h1>

      <p class="slogan">记录成长轨迹，助力未来发展</p>
      <p class="desc">全面、客观地记录和评价学生的综合素质发展，为学生的成长和未来发展提供有力支持。</p>
      <ul class="features">
        <li>
          <div>
            <span class="dot"></span>
            <h2>多维度评价体系</h2>
          </div>
          <p class="feature-desc">涵盖学业、品德、体育、艺术等多个维度的综合评价</p>
        </li>
        <li>
          <div>
            <span class="dot"></span>
            <h2>成长轨迹记录</h2>
          </div>
          <p class="feature-desc">完整记录学生成长过程中的重要事件和成就</p>
        </li>
        <li>
          <div>
            <span class="dot"></span>
            <h2>客观公正评估</h2>
          </div>
          <p class="feature-desc">科学的评价模型，确保评价结果客观公正</p>
        </li>
      </ul>
    </div>
    <!-- 右侧表单区域 -->
    <div class="right-section">
      <div class="right-section-content">
        <div class="tab-header" v-if="isPwd == true">
          <span :class="['tab-item', { active: currentTab === 'login' }]" @click="changeTab('login')">登录</span>
          <span :class="['tab-item', { active: currentTab === 'register' }]" @click="changeTab('register')">注册</span>
        </div>

        <div class="form-container" v-if="currentTab === 'register'">
          <h2 class="create-account-title">创建账号</h2>
          <p class="tip-text">请填写以下信息完成注册</p>
          <el-form ref="registerFormRules" :model="form" :rules="rules" class="register-form">
            <!-- <el-form-item label="学号" prop="studentId">
              <template #label>
                <span>学号</span>
              </template>
<el-input v-model="form.studentId" placeholder="请输入学号"></el-input>
</el-form-item>
<el-form-item label="姓名" prop="name">
  <template #label>
                <span>姓名</span>
              </template>
  <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
</el-form-item>
<el-form-item label="年级" prop="grade">
  <template #label>
                <span>年级</span>
              </template>

  <el-select v-model="form.grade" placeholder="请选择年级">
    <el-option label="一年级" value="1"></el-option>
    <el-option label="二年级" value="2"></el-option>
    <el-option label="三年级" value="3"></el-option>
  </el-select>
</el-form-item> -->
            <el-form-item label="用户名/学号" prop="account">
              <el-input v-model="form.account" placeholder="请输入账号"></el-input>
            </el-form-item>
            <el-form-item label="设置密码" prop="password">
              <template #label>
                <span>设置密码</span>
              </template>
              <el-input v-model="form.password" type="password" placeholder="请设置密码（至少8位，包含字母和数字）"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <template #label>
                <span>确认密码</span>
              </template>
              <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入密码"></el-input>
            </el-form-item>
            <!-- 新增身份证号字段 -->
            <el-form-item label="身份证号" prop="idCard">
              <template #label>
                <span>身份证号</span>
              </template>
              <el-input v-model="form.idCard" type="text" placeholder="请输入身份证号"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="phoneno">
              <template #label>
                <span>手机号码</span>
              </template>
              <el-input v-model="form.phoneno" type="text" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="安全问题（用于找回密码）" prop="securityQuestion">
              <el-select v-model="form.securityQuestion" placeholder="请选择安全问题">
                <el-option :label="item" v-for="item in securityQuestion" :key="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="安全问题答案" prop="securityAnswer">
              <el-input v-model="form.securityAnswer" placeholder="请输入安全问题的答案"></el-input>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="form.agreeProtocol">我已阅读并同意<el-link type="primary"
                  href="javascript:;">《用户服务协议》</el-link>和<el-link type="primary"
                  href="javascript:;">《隐私政策》</el-link></el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click.stop="handleRegister"
                style="width: 100%;background-color: #26c08d;height: 40px;font-size: 20px;">注册</el-button>
            </el-form-item>
            <el-form-item>
              <p>已有账号？<el-link type="primary" href="javascript:;" @click="currentTab = 'login'">立即登录</el-link></p>
            </el-form-item>
          </el-form>
        </div>
        <!-- 若需要登录 tab 内容，可补充对应表单，这里简单预留结构 -->
        <div class="form-container" v-else>
          <div v-if="isPwd">
            <h2 class="create-account-title">欢迎回来</h2>
            <p class="tip-text">请输入您的账号信息登录系统</p>
            <!-- 登录表单内容，可自行完善 -->
            <el-form ref="loginFormRules" :model="loginForm" :rules="loginRules" class="login-form">
              <el-form-item label="用户名/学号" prop="account">
                <el-input v-model="loginForm.account" placeholder="请输入账号"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="pwd">
                <el-input v-model="loginForm.pwd" type="password" placeholder="请输入密码"></el-input>
              </el-form-item>
              <el-form-item label="" prop="isChecked">
                <el-checkbox v-model="loginForm.isChecked">记住我</el-checkbox>
                <el-link type="primary" href="javascript:;" @click="isPwd = false">忘记密码</el-link>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleLogin"
                  style="width: 100%; height: 40px; background-color: #3b82f6;font-size: 20px;">登录</el-button>
              </el-form-item>
              <el-form-item>
                <p>还没有账号？<el-link type="primary" href="javascript:;" @click="currentTab = 'register'">立即注册</el-link></p>
              </el-form-item>
            </el-form>
          </div>

          <div v-else>
            <h2 class="create-account-title">找回密码</h2>
            <p class="tip-text">请通过安全问题找回您的密码</p>
            <!-- 登录表单内容，可自行完善 -->
            <el-form ref="pwdFormRules" :model="pwdForm" :rules="pwdRules" class="login-form">
              <el-form-item label="用户名/学号" prop="account">
                <el-input v-model="pwdForm.account" placeholder="请输入账号"></el-input>
              </el-form-item>
              <el-form-item label="安全问题" prop="securityQuestion">
                <el-select v-model="pwdForm.securityQuestion" placeholder="请选择安全问题">
                  <el-option :label="item" v-for="item in securityQuestion" :key="item" :value="item"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="安全问题答案" prop="securityAnswer">
                <el-input v-model="pwdForm.securityAnswer" type="text" placeholder="请输入安全问题答案"></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="pwd">
                <el-input v-model="pwdForm.pwd" type="password" placeholder="请设置新密码(至少8位，包含字母和数字)"></el-input>
              </el-form-item>

               <el-form-item label="确认密码" prop="confirmPassword">
              <template #label>
                <span>确认密码</span>
              </template>
              <el-input v-model="pwdForm.confirmPassword" type="password" placeholder="请再次输入密码"></el-input>
            </el-form-item>

              <el-form-item>
                <el-button type="info" @click="isPwd = true">返回登录</el-button>
                <el-button type="primary" @click="handleResetPwd">重置密码</el-button>
              </el-form-item>

            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElCheckbox, ElLink, ElButton, ElMessage } from 'element-plus';
import { useWindowSize } from '@vueuse/core';
import { useRouter } from 'vue-router';
import encrypor from '@/config/rsaEncrypt.js';
// 导入API
import { login, register,resetPassword } from '@/api/user';
import { useStore } from "@/store";


const router = useRouter();

const { width } = useWindowSize();
const isMobile = ref(false);
// 根据窗口宽度判断是否为移动端，可自行调整阈值，比如 768px 以下视为移动端
watch(width, (val) => {
  isMobile.value = val < 768;
});

const currentTab = ref('login'); // 默认显示注册 tab，可根据需求调整
const isPwd = ref(true); // 默认显示密码登录，可根据需求调整
const loginFormRules = ref(null)  // 关键：定义ref引用
const pwdFormRules = ref(null)
const registerFormRules = ref(null)

// 密保问题
const securityQuestion = ref(['最好朋友的生日？', '您最喜欢的运动是什么？', '最难忘的一个人？', '最难忘的一个人？', '最喜欢的歌曲？', '您最喜欢的书籍是什么？', '您最尊敬的教育家是谁？', '您最好的朋友的名字是什么？', '您最喜欢的音乐类型是什么？', '您最喜欢的教育理念是什么？']);

const form = reactive({
  studentId: '',
  name: '',
  grade: '',
  password: '',
  idCard: '', // 新增身份证号字段
  confirmPassword: '',
  securityQuestion: '',
  securityAnswer: '',
  agreeProtocol: false
});
const loginForm = reactive({
  account: '',
  pwd: '',
  isChecked: false
});

const pwdForm = reactive({
  account: '',
  securityQuestion: '',
  securityAnswer: '',
  pwd: '',
  confirmPassword: ''
});

const rules = reactive({
  account: [
    { required: true, message: '请输入用户名/学号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,}$/, message: '密码至少8位，包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  phoneno: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
  ],
  // 新增身份证号验证规则
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],

  securityQuestion: [
    { required: true, message: '请选择安全问题', trigger: 'change' }
  ],
  securityAnswer: [
    { required: true, message: '请输入安全问题答案', trigger: 'blur' }
  ],
  agreeProtocol: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请同意用户服务协议和隐私政策'));
        } else {
          callback();
        }
      },
      message: '密码至少8位，包含字母和数字',
      trigger: 'change'
    }
  ]
});

const loginRules = reactive({
  account: [
    { required: true, message: '请输入用户名/学号', trigger: 'blur' }
  ],
  pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  // 添加isChecked的验证规则
  isChecked: [
    {
      validator: (rule, value, callback) => {
        callback(); // 总是通过，因为只是"记住我"选项
      }, trigger: 'change'
    }
  ]
});

const pwdRules = reactive({
  account: [
    { required: true, message: '请输入用户名/学号', trigger: 'blur' }
  ],
  securityQuestion: [
    { required: true, message: '请选择安全问题', trigger: 'change' }
  ],
  securityAnswer: [
    { required: true, message: '请输入安全问题答案', trigger: 'blur' }
  ],
  pwd: [
    { required: true, message: '请设置新密码', trigger: 'blur' }
  ],
    confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.pwd) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
})

const changeTab = (tab) => {
  currentTab.value = tab;
}

// 注册
const handleRegister = () => {
  registerFormRules.value.validate((valid) => {
    if (valid) {
      const securityAnswer = encrypor.encrypt(form.securityAnswer)
      // 调用API进行注册
      register({
        username: form.account,
        password: form.password,
        phoneno: form.phoneno,
        idcard: form.idCard,
        question: form.securityQuestion,
        answer: securityAnswer
      }).then(res => {
        if (res.code > 0) {
          ElMessage.success('注册成功，请登录'); // 这里可以添加注册成功的逻辑
          currentTab.value = 'login';
          loginForm.account = form.account
          form.password = ''
        } else {
          ElMessage.error(res.message || '注册失败');
        }
      }).catch(error => {
        ElMessage.error('网络错误，请重试');
        console.error('Register error:', error);
      });
    }
  });
};

// 登录
const handleLogin = () => {
  debouncedLogin()
}

const debouncedLogin = () => {
  let isRequesting = false;
  return function(){
    if (isRequesting) return;
    loginFormRules.value.validate((valid) => {
    if (valid) {
      isRequesting = true;
      const account = encrypor.encrypt(loginForm.account)
      const pwd = encrypor.encrypt(loginForm.pwd)
      // 使用API请求
      login({
        username: account,
        userpwd: pwd
      }).then(response => {
          isRequesting = false;
        if (response.code > 0) {
          // 存储到 Vuex  初始化user store
          const store = useStore();
          store.user.setUserInfo({
            username: response.data.nickname,
            password: loginForm.pwd,
            student_id: response.data.studentid,
            token: response.data.token,
            isChecked: loginForm.isChecked
          });
          // 保存登录状态
          sessionStorage.setItem('token', JSON.stringify({
            username: response.data.nickname,
            password: loginForm.pwd,
            student_id: response.data.studentid,
            token: response.data.token,
            isChecked: loginForm.isChecked
          }));
          ElMessage.success(response.msg);
          router.push('/');

        } else {
          ElMessage.error(response.msg || '账号或密码错误');
        }
      }).catch(error => {
         isRequesting = false;
        ElMessage.error('网络错误，请重试');
      });
    }
  });
  }();
};


// 新增重置密码处理函数
const handleResetPwd = () => {
  pwdFormRules.value.validate((valid) => {
    if (valid) {
      resetPassword({
        username: pwdForm.account,
        question: pwdForm.securityQuestion,
        answer: encrypor.encrypt(pwdForm.securityAnswer),
        newpassword: encrypor.encrypt(pwdForm.pwd)
      }).then(res => {
        console.log(res)
        if (res.code > 0) {
          ElMessage.success('密码重置成功，请使用新密码登录');
          isPwd.value = true;
        } else {
          ElMessage.error(res.message || '密码重置失败');
        }
      })
    }
  });
};

// 页面加载时检查是否有记住的账号
onMounted(() => {
  const token = sessionStorage.getItem('token');
  if (token) {
    const { username, isChecked } = JSON.parse(token);
    if (username && isChecked) {
      loginForm.username = username;
    }
  }
});
</script>


<style scoped lang="scss">
.register-container {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(to right, #4c76f4, #e3f2fd);
  /* 简单渐变背景，可替换成设计图的渐变 */
}

::v-deep .el-form-item--label-right .el-form-item__label {
  width: auto;
  justify-content: flex-start;
  text-align: left;
}

/* 左侧区域样式 */
.left-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 0 100px 0 50px;
  color: #fff;
}

.system-title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 20px;
}

.slogan {
  font-size: 35px;
  font-weight: 600;
  margin-bottom: 30px;
  line-height: 1.5;
}

.desc {
  font-size: 18px;
  margin-bottom: 40px;
  line-height: 1.7;
}

.features {
  list-style: none;
  padding: 0;
}

.features li {
  display: flex;
  align-items: flex-start;
  flex-direction: column;
  margin-bottom: 20px;

  >div {
    display: flex;
    align-content: center;
    margin: 8px 0;

    .dot {
      width: 12px;
      height: 12px;
      line-height: 12px;
      background-color: #fff;
      border-radius: 50%;
      margin-right: 10px;
      margin-top: 10px;
    }
  }
}



.feature-desc {
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
}

/* 右侧区域样式 */
.right-section {
  flex: 1;
  background-color: #fff;
  padding: 10px 30px;
  box-sizing: border-box;
  overflow-y: auto;
  position: relative;

  .right-section-content {
    max-width: 500px;
    width: 500px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    .el-form-item {
      display: flex;
      flex-direction: column;

      .el-input,
      .el-select {
        height: 40px;
      }

      ::v-deep .el-select .el-select__wrapper {
        height: 100%;
      }

      ::v-deep .el-form-item__content {
        justify-content: space-between;
      }
    }

    ::v-deep .el-form-item--label-right .el-form-item__label {
      width: auto;
      justify-content: flex-start;
      text-align: left;
    }

    h1 {
      text-align: center;
      margin-bottom: 20px;
    }
  }

}

.tab-header {
  display: flex;
  border-bottom: 1px solid #e6e6e6;
  margin-bottom: 30px;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  cursor: pointer;
  color: #999;
}

.tab-item.active {
  color: #409eff;
  border-bottom: 2px solid #409eff;
}

.create-account-title,
.login-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.tip-text {
  font-size: 14px;
  color: #999;
  margin-bottom: 20px;
}

.register-form,
.login-form {
  width: 100%;
}

/* 响应式处理，移动端隐藏左侧，调整右侧为满宽 */
@media (max-width: 767px) {
  .left-section {
    display: none;
  }

  .right-section {
    width: 100%;

    .el-form-item {
      display: flex;
      flex-direction: column;
      margin-bottom: 8px;

      ::v-deep .el-form-item__content {
        justify-content: space-between;
      }
    }

    ::v-deep .el-form-item--label-right .el-form-item__label {
      width: auto;
      justify-content: flex-start;
      text-align: left;
    }
  }
}

/* 用于移动端隐藏左侧的辅助类 */
.hide-on-mobile {
  display: none;
}
</style>
